import {
  CHANGETOKEN, CHANGEUSERINFO, GETUSERINFO, CHANGEUSERIMG,
  ADDUSERHISTORY, SETUSERCOLLECT, GETORDERACTION, CHANGEORDERACTION
} from '../mutation-type'
import { post, postFile, put } from '@/utils/axios'
import Vue from "vue";
import {
  Toast
} from "vant";
Vue.use(Toast);


const module = {
  namespaced: true, // 命名空间
  state: {
    token: '',
    userinfo: {},
    aOrder: []
  },
  actions: {
    [GETUSERINFO](context, payload) {
      post({
        url: '/hybrid/uni/userinfo'
      }).then(res => {
        context.commit('CHANGEUSERINFO', res.result)
      })
    },
    [CHANGEUSERIMG](context, payload) {
      // console.log(payload)
      postFile({
        url: `/hybrid/uni/upload`,
        // ?type=${payload.type}
        data: payload
      }).then(res => {
        context.dispatch('GETUSERINFO')
      })
    },
    [ADDUSERHISTORY](context, payload) {
      // 设置了content-type为json,就不能直接传字段传
      put({
        url: '/hybrid/uni/add-history',
        // data: payload
        data: {
          _id: payload
        }
      }).then((res) => {
        if (res.result.n) {
          context.dispatch('GETUSERINFO')
        }
      })
    },
    [SETUSERCOLLECT](context, payload) {
      // 设置了content-type为json,就不能直接传字段传
      put({
        url: '/hybrid/uni/set-collections',
        // data: payload
        data: {
          ...payload
        }
      }).then((res) => {
        if (res.result.n) {
          Toast({
            message: res.msg,
            duration: 500,
            position: "bottom"
          });
          context.dispatch('GETUSERINFO')
        }
      })
    },
    [GETORDERACTION](context, payload) {
      post({
        url: '/hybrid/uni/get-orders'
      }).then(res => {
        if (res.status >= 0) {
          context.commit('CHANGEORDERACTION', res.result)
        }
      })
    }
  },
  mutations: {
    [CHANGETOKEN](state, payload) {
      state.token = payload
    },
    [CHANGEUSERINFO](state, payload) {
      state.userinfo = payload
    },
    [CHANGEORDERACTION](state, payload) {
      state.aOrder = payload
    }
  },
  getters: {
    orderType: ({ aOrder }) => (type) => {
      return aOrder.length > 0 && aOrder.filter(item => item.type === type)
    }
  }
}

export default module
